package com.zhai.domain.activity.service.armory;

import com.zhai.domain.activity.model.entity.ActivityCountEntity;
import com.zhai.domain.activity.model.entity.ActivityEntity;
import com.zhai.domain.activity.model.entity.ActivitySkuEntity;
import com.zhai.domain.activity.repository.IActivityRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;

import static com.zhai.types.common.Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY;

/**
 * @Description: 活动装配
 * @ClassName: ActivityArmory
 * @Author: zhaiyongxin
 * @Date: 2025/2/24 15:09
 * @Version: 1.0
 */
@Service
@Slf4j
public class ActivityArmory implements IActivityArmory, IActivityDispatch{
    @Resource
    IActivityRepository activityRepository;

    @Override
    public boolean assembleActivitySku(Long sku) {
        // 缓存活动sku库存
        ActivitySkuEntity activitySkuEntity = activityRepository.queryActivitySku(sku);
        cacheActivitySkuStockCount(sku, activitySkuEntity.getStockCountSurplus());

        // 缓存活动信息
        ActivityEntity activityEntity = activityRepository.queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());

        // 缓存活动数量信息
        ActivityCountEntity activityCountEntity = activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        return true;
    }

    /**
     * 通过活动id装配活动sku
     * @param activityId
     * @return
     */
    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
        List<ActivitySkuEntity> activitySkuEntityList =  activityRepository.queryActivitySkuByActivityId(activityId);
        for (ActivitySkuEntity activitySkuEntity : activitySkuEntityList) {
            cacheActivitySkuStockCount(activitySkuEntity.getSku(), activitySkuEntity.getStockCountSurplus());
            // 缓存活动数量信息
            ActivityCountEntity activityCountEntity = activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        }
        // 缓存活动信息
        ActivityEntity activityEntity = activityRepository.queryRaffleActivityByActivityId(activityId);
        return true;
    }

    private void cacheActivitySkuStockCount(Long sku, Integer stockCount) {
        String cacheKey = ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        activityRepository.cacheActivitySkuStockCount(cacheKey, stockCount);
    }

    /**
     * 扣减sku库存
     *
     * @param sku
     * @param endTime
     * @return
     */
    @Override
    public boolean subtractActivitySkuStock(Long sku, Date endTime) {
        String cacheKey = ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        return activityRepository.subtractActivitySkuStock(sku, cacheKey, endTime);
    }
}
